#include<bits/stdc++.h>
using namespace std;
char c[10000];
int main()
{
	long long t,np,nq,m,i;
	cin>>t;
	while(t--)
	{
		long long sum1=0,sum2=0,sum=0;
		cin>>m>>np;
		cin>>c;
		for(i=0;i<np;i++)
		sum1=(sum1*10+c[i]-'0')%m;
		cin>>nq;
		memset(c,0,sizeof(c));
		cin>>c;
		for(i=0;i<nq;i++)
		sum2=(sum2*10+c[i]-'0')%m;
		sum=(sum1*sum2)%m;
		cout<<sum<<endl;
	}
    return 0;
}
